package com.ticket.controller.api;

import com.ticket.entity.TicketPrice;
import com.ticket.service.ISeatAllocationService;
import com.ticket.service.ITicketPriceService;
import com.ticket.service.IVenueSectionService;
import com.ticket.utils.Result;
import com.ticket.vo.SectionAvailabilityVO;
import com.ticket.vo.TicketPriceVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/tickets/prices")
public class TicketPriceController {

    @Autowired
    private ITicketPriceService ticketPriceService;
    
    @Autowired
    private IVenueSectionService venueSectionService;
    
    @Autowired
    private ISeatAllocationService seatAllocationService;

    @GetMapping("/{matchId}")
    public Result<List<TicketPriceVO>> getTicketPricesByMatchId(@PathVariable Long matchId) {
        List<TicketPriceVO> ticketPrices = ticketPriceService.getTicketPricesByMatchId(matchId);
        
        // 为每个区域添加可用座位信息
        for (TicketPriceVO priceVO : ticketPrices) {
            // 获取区域总容量
            Integer capacity = venueSectionService.getSectionCapacity(priceVO.getSectionId());
            
            // 获取已售座位数
            Integer soldSeats = seatAllocationService.getSoldSeatCount(matchId, priceVO.getSectionId());
            
            // 计算可用座位数
            Integer availableSeats = capacity - soldSeats;
            
            priceVO.setTotalCapacity(capacity);
            priceVO.setAvailableSeats(availableSeats);
            priceVO.setSoldOut(availableSeats <= 0);
        }
        
        return Result.success(ticketPrices);
    }
    
    @GetMapping("/{matchId}/sections/{sectionId}/availability")
    public Result<SectionAvailabilityVO> getSectionAvailability(
            @PathVariable Long matchId, 
            @PathVariable Long sectionId) {
        
        SectionAvailabilityVO availability = new SectionAvailabilityVO();
        availability.setMatchId(matchId);
        availability.setSectionId(sectionId);
        
        // 获取区域总容量
        Integer capacity = venueSectionService.getSectionCapacity(sectionId);
        availability.setTotalCapacity(capacity);
        
        // 获取已分配座位
        List<Integer> occupiedSeats = seatAllocationService.getOccupiedSeats(matchId, sectionId);
        availability.setOccupiedSeats(occupiedSeats);
        
        // 计算可用座位
        List<Integer> availableSeats = new ArrayList<>();
        for (int i = 1; i <= capacity; i++) {
            if (!occupiedSeats.contains(i)) {
                availableSeats.add(i);
            }
        }
        availability.setAvailableSeats(availableSeats);
        
        return Result.success(availability);
    }
} 